//
//  SendCoinView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/5/4.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class SendCoinView: BaseView, UITableViewDataSource, UITableViewDelegate, GoolPassWordDelegate {
    var viewModel:SendCoinViewModel?
    var addressText:BaseTextField?
    var coinText:BaseTextField?
    var kindText:BaseTextField?
    lazy var tableView:UITableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.grouped)
    lazy var selectBtn:UIButton = {
        let btn =  CommonBtn.creatSelectBtnWithTitle(title: kText("发送"), y: 62, view: self, sel:  #selector(selectBtnAction))
        return btn
    }()

    lazy var footView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 260))
        return view
    }()
    
    lazy var useLabel: UILabel = {
        let label = BaseLabel(style: .twiceStyle)
        label.font = UIFont.systemFont(ofSize: 11)
        return label
    }()
    
    lazy var allBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle(kText("全部"), for: UIControlState.normal)
        btn.addTarget(self, action: #selector(allMoenyAction), for: UIControlEvents.touchUpInside)
        btn.setTitleColor(kThemeColor, for: UIControlState.normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 11)
        return btn
    }()
    
    lazy var networkLabel: UILabel = {
        let label = BaseLabel(style: .oneStyle)
        label.text = kText("网络费")
        label.font = UIFont.systemFont(ofSize: 14)
        return label
    }()
    
    lazy var networkMoney: UILabel = {
        let label = BaseLabel(style: .oneStyle)
        label.text = String(format: "%@ %@","0",(viewModel?.model.coinCode)!)
        label.font = UIFont.systemFont(ofSize: 14)
        return label
    }()
    
    lazy var informationLabel: UILabel = {
        let label = BaseLabel(style: .thirdStyle)
        label.numberOfLines = 0
        label.font = UIFont.systemFont(ofSize: 11)
        return label
    }()
    
   
    override func setUpUI() -> Void {
        self.viewModel = dataSource as? SendCoinViewModel
        NotificationCenter.default.addObserver(self, selector: #selector(refresh(note:)), name: NSNotification.Name.Exchange.addressDidSelect, object: nil)
        viewModel?.addObserver(self, forKeyPath: "refreshBool", options: [.new,.old], context: nil)
        
        self.themeBackground = ThemeManager.ThemeColorKeys.background
        
        self.addSubview(tableView)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.themeBackground = ThemeManager.ThemeColorKeys.background
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.top.equalToSuperview()
        }
        
        tableView.tableFooterView = footView
        
        footView.addSubview(selectBtn)
        
        footView.addSubview(networkLabel)
        networkLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(36)
        }
        
        footView.addSubview(networkMoney)
        networkMoney.snp.makeConstraints { (make) in
            make.centerY.equalTo(networkLabel)
            make.right.equalToSuperview().offset(-16)
        }
        
        footView.addSubview(informationLabel)
        informationLabel.snp.makeConstraints { (make) in
            make.top.equalTo(selectBtn.snp.bottom).offset(40)
            make.left.equalToSuperview().offset(16)
            make.width.equalTo(kSCREEN_WIDTH-32)
        }
        
        
    }
    
    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "refreshBool" {
            self.networkMoney.text = String(format: "%@ %@",(self.viewModel?.poundage)!,(self.viewModel?.model.coinCode)!)
        }
        
    }
    
    //MARK tableViewDelegate
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 || section == 2{
            return 1
        }
        return 2
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let identy = "identyCell"
            var cell = tableView.dequeueReusableCell(withIdentifier: identy) as? BaseTableViewCell
            if cell == nil {
                cell = BaseTableViewCell(style: .default, reuseIdentifier: identy)
                cell?.nameLabel.snp.remakeConstraints { (make) in
                    make.left.equalToSuperview().offset(46)
                    make.centerY.equalToSuperview()
                }
                cell?.setArrowImage()
                cell?.contentView.addSubview((cell?.iconImage)!)
                cell?.iconImage.layer.cornerRadius = 10
                cell?.iconImage.layer.masksToBounds = true
                cell?.iconImage.snp.makeConstraints({ (make) in
                    make.left.equalToSuperview().offset(15)
                    make.centerY.equalToSuperview()
                    make.width.height.equalTo(20)
                })
                cell?.line.isHidden = true
                cell?.selectionStyle = .none
            }
            cell?.nameLabel.text = viewModel?.model.coinCode
            cell?.iconImage.sd_setImage(with: URL(string: (viewModel?.model.logoUrl)!), placeholderImage:UIImage(named: "coinIcon"))
            return cell!
            
        }else if indexPath.section == 1{
            if indexPath.row == 0 {
                let identy = "identyWY"
                var cell = tableView.dequeueReusableCell(withIdentifier: identy) as? WritePasteTableViewCell
                if cell == nil {
                    cell = WritePasteTableViewCell(style: .default, reuseIdentifier: identy)
                    cell?.delegate = self
                    addressText = cell?.textField
                    cell?.textField.addTarget(self, action: #selector(textFieldDidChangeValue(textField:)), for:UIControlEvents.editingChanged)
                }
                cell?.textField.text = viewModel?.address
                cell?.setModel(model: (viewModel?.model)!)
                cell?.selectionStyle = .none
                return cell!
            }else {
                let identy = "identyCH"
                var cell = tableView.dequeueReusableCell(withIdentifier: identy) as? WriteChangeTableViewCell
                if cell == nil {
                    cell = WriteChangeTableViewCell(style: .default, reuseIdentifier: identy)
                    cell?.coninText.delegate = self
                    cell?.breedText.delegate = self
                    coinText = cell?.coninText
                    kindText = cell?.breedText
                    cell?.breedText.isEnabled = false
                    cell?.coninText.addTarget(self, action: #selector(textFieldDidChangeValue(textField:)), for:UIControlEvents.editingChanged)
                    
                    cell?.breedText.addTarget(self, action: #selector(textFieldDidChangeValue(textField:)), for:UIControlEvents.editingChanged)
                    
                }
                cell?.setModel(model: (viewModel?.model)!)
                cell?.coninText.text = viewModel?.coinMoney
                cell?.breedText.text = viewModel?.kindMoney
                cell?.selectionStyle = .none
                return cell!
            }
        }else {
            
            let identy = "identyBz"
            var cell = tableView.dequeueReusableCell(withIdentifier: identy) as? NameWriteCell
            if cell == nil {
            cell = NameWriteCell(style: .default, reuseIdentifier: identy)
            cell?.selectionStyle = .none
            cell?.nameLabel.text = kText("备注")
            cell?.textField.placeholder = kText("请输入备注")
            cell?.textField.themeTextColor  = ThemeManager.ThemeColorKeys.text1
                cell?.textField.snp.remakeConstraints({ (make) in
                    make.left.equalTo(cell!.nameLabel.snp.right).offset(5)
                    make.right.equalToSuperview().offset(-15)
                    make.centerY.equalToSuperview()
                })
            cell?.backArrorImage.isHidden = true
                cell?.textField.addTarget(self, action: #selector(textFieldDidChangeValue(textField:)), for:UIControlEvents.editingChanged)
                cell?.textField.delegate = self
                cell?.textField.setPlaceholderColor()
                
            }
            cell?.textField.text = viewModel?.remarks
            return cell!
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 || indexPath.section == 2{
            return 50
        }
        return 72
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            
            return 20
        }
        return 0.1
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            return 20
        }else if section == 1 {
            return 30
        }else {
        return 0.1
        }
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 20))
        view.themeBackground = ThemeManager.ThemeColorKeys.background
        return view
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0 {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 20))
        view.themeBackground = ThemeManager.ThemeColorKeys.background
        return view
        }else if section == 1{
            let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 30))
            view.themeBackground = ThemeManager.ThemeColorKeys.background
            view.addSubview(useLabel)
            useLabel.snp.makeConstraints { (make) in
                make.top.equalToSuperview().offset(10)
                make.right.equalToSuperview().offset(-55)
            }
            
            let line = UIView()
            line.themeBackground = ThemeManager.ThemeColorKeys.tabLineColor
            view.addSubview(line)
            line.snp.makeConstraints { (make) in
                make.right.equalToSuperview().offset(-48)
                make.top.equalToSuperview().offset(10)
                make.height.equalTo(11)
                make.width.equalTo(0.5)
            }
            
            view.addSubview(allBtn)
            allBtn.snp.makeConstraints { (make) in
                make.top.equalToSuperview()
                make.right.equalToSuperview()
                make.width.equalTo(48)
                make.height.equalTo(31)
            }
            return view
            
        }
        return nil
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0  {
            let controller = SelectCoinViewController()
            controller.dateArr = APPAssetInfo.default.coinAssetArr
            controller.selectIndex = (viewModel?.selectIndex)!
            controller.selectBlock = {(index) in
                if self.viewModel?.selectIndex == index {
                    return
                }
                self.viewModel?.model =  APPAssetInfo.default.coinAssetArr[index]
                self.viewModel?.selectIndex = index
                self.viewModel?.changeModel()
                self.viewModel?.clear()
                self.viewModel?.archiCharge()
                self.networkMoney.text = String(format: "%@ %@",(self.viewModel?.poundage)!,(self.viewModel?.model.coinCode)!)
                self.setModel()
            }
            self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
        }
    }
    
    func setModel() {
        tableView.reloadData()
        useLabel.text = "\(kText("可用"))  " + CYCalculate.cy_intercept(number: (viewModel?.model.currentAmount)!, digit: self.viewModel?.tradeModel.coinPrecision ?? 8)!
        self.changeInformation()
    }
    
    @objc func selectBtnAction() {
        viewModel?.checkStates(returnValue: { (canSend) in
            if canSend {
                AppSecurityInfo.default.codeType = 11
                if AppSecurityInfo.default.model.isOpenGoogle {
                    GooglePassWordManager.creatGoolPassWord(dataSource: self, style: .googleDoubleAuthen,validate: .googleStyle)
                }else {
                    GooglePassWordManager.creatGoolPassWord(dataSource: self, style: .googleDoubleAuthen,validate: .telStyle)
                }
            }
        })
        
        
    }
    
    @objc func refresh(note:NSNotification) {
        let data = note.object
        if ((data as? CoinCodeModel) != nil) {
            self.viewModel?.address = ((data as? CoinCodeModel)?.drawAdd)!
            self.viewModel?.remarks = ((data as? CoinCodeModel)?.remarks)!
            self.tableView.reloadData()
        }
    }
    
    func changeInformation() {
        viewModel?.archiveSmallPrice(block: {
            var coinChName = self.viewModel?.tradeModel.coinName ?? ""
            if AppCacheInfo.default.isEnlish {
                coinChName = self.viewModel?.tradeModel.coinFullName ?? ""
            }
            let coinName = self.viewModel?.tradeModel.coinCode ?? ""
            let text = String(format: kText("1.请确保正在发送的是一个%@(%@) 地址，否则资产将会丢失且无法找回。\n2.最小提币金额为  %@ %@ \n3.与平台内的用户进行转账，不收取网络手续费"),coinChName,coinName,(self.viewModel?.smallPrice)!,coinName)
            self.informationLabel.text = text
            self.informationLabel.changeLabelTextStyle(title: String(format: "%@(%@)", coinChName,coinName), color: kThemeColor, font: UIFont.systemFont(ofSize: 11),isSpace:true)
        })
    }
    
    
    func googleVerificationt(passWord: String) {
        let arr = (passWord as NSString).components(separatedBy: "/")
        if (arr.count) < 2 {
            CYMBShow.showMessage(kText("安全验证错误,请重新验证"))
            return
        }
        viewModel?.passWord = (arr.first)!
        viewModel?.codeNumber = (arr.last)!
        viewModel?.sendCoin()
    }
    
    @objc func allMoenyAction() {
        viewModel?.coinMoney = CYCalculate.cy_intercept(number: (viewModel?.model.currentAmount)!, digit: 8)!
        viewModel?.archiveLeveMoeny(coin: (viewModel?.coinMoney)!)
//        viewModel?.chargeNumber()
        coinText?.text = viewModel?.coinMoney
        kindText?.text = viewModel?.kindMoney
    }
    
    
    
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.Exchange.addressDidSelect, object: nil)
        viewModel?.removeObserver(self, forKeyPath: "refreshBool")
        
        dPrint("销毁了\(self)")
        
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
extension SendCoinView:OpenQrDelegate, UITextFieldDelegate {
    func openQr() {
        let c =  QRCodeViewController()
        c.completion = {[unowned self](result)in
            self.viewModel?.address = result
            self.tableView.reloadData()
        }
        self.viewModel?.controller?.present(c, animated: true, completion: nil)
    }
    
    func selectAddress() {
        let controller = ExtractCoinViewController()
        controller.viewModel?.selectBool = true
        controller.viewModel?.coinCode = (viewModel?.model.coinCode)!
        self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
//        let controller = CoinAddressViewController()
//        controller.viewModel?.selectBool = true
//        self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
        if textField.isEqual(addressText) {
            
        }else if textField.isEqual(coinText) {
            return textField.cheakNumberFormat(digit: self.viewModel!.tradeModel.coinPrecision != nil ? self.viewModel!.tradeModel.coinPrecision! : 8,
                range: range, string: string, interger: 10)
        }else {
            return true
        }
        return true
    }
    
    @objc func textFieldDidChangeValue(textField:UITextField) {
        if textField.isEqual(addressText) {
            viewModel?.address = textField.text!
        }else if textField.isEqual(coinText) {
            viewModel?.coinMoney = textField.text!
            viewModel?.archiveLeveMoeny(coin: textField.text!)
//            viewModel?.chargeNumber()
            coinText?.text = viewModel?.coinMoney
            kindText?.text = viewModel?.kindMoney
        }else {
            viewModel?.remarks = textField.text!
        }
    }
    
}
